package reference;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import reference.vo.UieComponentVo;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hujian
 * @date 2023/2/18 10:32
 * @description
 */
@Slf4j
public class UieUtil {

    private static final String UIE_TITLE_URI = "http://192.168.11.247:8189/taskflow/uie";
    private static final String UIE_MULTI_URI = "http://192.168.11.247:1503/taskflow/uie";
    private static final String UIE_MULTI_EN_URI = "http://192.168.11.247:1504/taskflow/uie";

    public static List<UieComponentVo> getOneUieAuthorInfo(String text) {
        List<String> texts = new ArrayList<>();
        texts.add(text);
        List<List<UieComponentVo>> uieTitleInfo = getUieAuthorInfo(texts);
        if (null != uieTitleInfo) {
            return uieTitleInfo.get(0);
        } else {
            return new ArrayList<>();
        }

    }

    /**
     * 识别人名
     *
     * @param texts 输入
     * @return 列表
     */
    public static List<List<UieComponentVo>> getUieAuthorInfo(List<String> texts) {

        JSONObject requestJson = new JSONObject();
        JSONArray textArray = new JSONArray();
        textArray.addAll(texts);
        JSONObject text = new JSONObject();
        text.put("text", textArray);
        requestJson.put("data", text);

        HttpPost post = new HttpPost(UIE_TITLE_URI);
        post.setEntity(new StringEntity(requestJson.toString(), ContentType.APPLICATION_JSON));
        CloseableHttpClient httpClient = HttpUtils.getHttpClient();
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
                JSONArray results = jsonObject.getJSONArray("result");

                List<List<UieComponentVo>> all_names = new ArrayList<>();
                for (Object value : results) {
                    JSONObject result = (JSONObject) value;
                    List<UieComponentVo> oneList = new ArrayList<>();
                    if (((JSONObject) value).size() == 0) {
                        all_names.add(oneList);
                        continue;
                    }
                    JSONArray jsonArray = (JSONArray) result.get("人名");
                    for (Object o : jsonArray) {
                        UieComponentVo uieTitleVo;
                        uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                        oneList.add(uieTitleVo);
                    }
                    //对oneList排序
                    oneList = oneList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                    all_names.add(oneList);
                }
                return all_names;
            }
            log.error("uie title response is not 200,textSize:{}, status:{}", texts.size(), response.getStatusLine().getStatusCode());
            return null;
        } catch (IOException | JSONException e) {
            log.error("uie title failed,textSize:{},error:{}", texts.size(), e.getMessage());
        }
        return null;
    }


    /**
     * 识别多个部分
     *
     * @param texts 输入
     * @return 列表对
     */
    public static List<Map<String, List<UieComponentVo>>> getUieExtractMap(List<String> texts) {

        JSONObject requestJson = new JSONObject();
        JSONArray textArray = new JSONArray();
        textArray.addAll(texts);
        JSONObject text = new JSONObject();
        text.put("text", textArray);
        requestJson.put("data", text);

        HttpPost post = new HttpPost(UIE_MULTI_URI);
        post.setEntity(new StringEntity(requestJson.toString(), ContentType.APPLICATION_JSON));
        CloseableHttpClient httpClient = HttpUtils.getHttpClient();
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
                JSONArray results = jsonObject.getJSONArray("result");

                List<Map<String, List<UieComponentVo>>> all_infos = new ArrayList<>();
                for (Object value : results) {
                    JSONObject result = (JSONObject) value;
                    Map<String, List<UieComponentVo>> listMap = new HashMap<>();
                    if (((JSONObject) value).size() == 0) {
                        all_infos.add(listMap);
                        continue;
                    }
                    Object author = result.get("人名");
                    if (null != author) {
                        JSONArray jsonArray = (JSONArray) author;
                        List<UieComponentVo> tmpList = new ArrayList<>();
                        for (Object o : jsonArray) {
                            UieComponentVo uieTitleVo;
                            uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                            tmpList.add(uieTitleVo);
                        }
                        //对oneList排序
                        tmpList = tmpList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                        listMap.put("authors", tmpList);
                    }
                    Object title = result.get("题目");
                    if (null != title) {
                        JSONArray jsonArray = (JSONArray) title;
                        List<UieComponentVo> tmpList = new ArrayList<>();
                        for (Object o : jsonArray) {
                            UieComponentVo uieTitleVo;
                            uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                            tmpList.add(uieTitleVo);
                        }
                        //对oneList排序
                        tmpList = tmpList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                        listMap.put("title", tmpList);
                    }
                    Object school = result.get("机构");
                    if (null != school) {
                        JSONArray jsonArray = (JSONArray) school;
                        List<UieComponentVo> tmpList = new ArrayList<>();
                        for (Object o : jsonArray) {
                            UieComponentVo uieTitleVo;
                            uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                            tmpList.add(uieTitleVo);
                        }
                        //对oneList排序
                        tmpList = tmpList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                        listMap.put("school", tmpList);
                    }
                    Object year = result.get("年份");
                    if (null != year) {
                        JSONArray jsonArray = (JSONArray) year;
                        List<UieComponentVo> tmpList = new ArrayList<>();
                        for (Object o : jsonArray) {
                            UieComponentVo uieTitleVo;
                            uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                            tmpList.add(uieTitleVo);
                        }
                        //对oneList排序
                        tmpList = tmpList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                        listMap.put("year", tmpList);
                    }
                    all_infos.add(listMap);
                }
                return all_infos;
            }
            log.error("uie title response is not 200,textSize:{}, status:{}", texts.size(), response.getStatusLine().getStatusCode());
            return null;
        } catch (IOException | JSONException e) {
            log.error("uie title failed,textSize:{},error:{}", texts.size(), e.getMessage());
        }
        return null;
    }


    /**
     * 识别英文多个部分
     *
     * @param texts 输入
     * @return 列表对
     */
    public static List<Map<String, List<UieComponentVo>>> getEnUieExtractMap(List<String> texts) {

        JSONObject requestJson = new JSONObject();
        JSONArray textArray = new JSONArray();
        textArray.addAll(texts);
        JSONObject text = new JSONObject();
        text.put("text", textArray);
        requestJson.put("data", text);

        HttpPost post = new HttpPost(UIE_MULTI_EN_URI);
        post.setEntity(new StringEntity(requestJson.toString(), ContentType.APPLICATION_JSON));
        CloseableHttpClient httpClient = HttpUtils.getHttpClient();
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
                JSONArray results = jsonObject.getJSONArray("result");

                List<Map<String, List<UieComponentVo>>> all_infos = new ArrayList<>();
                for (Object value : results) {
                    JSONObject result = (JSONObject) value;
                    Map<String, List<UieComponentVo>> listMap = new HashMap<>();
                    if (((JSONObject) value).size() == 0) {
                        all_infos.add(listMap);
                        continue;
                    }
                    Object author = result.get("author");
                    if (null != author) {
                        JSONArray jsonArray = (JSONArray) author;
                        List<UieComponentVo> tmpList = new ArrayList<>();
                        for (Object o : jsonArray) {
                            UieComponentVo uieTitleVo;
                            uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                            tmpList.add(uieTitleVo);
                        }
                        //对oneList排序
                        tmpList = tmpList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                        listMap.put("authors", tmpList);
                    }
                    Object title = result.get("title");
                    if (null != title) {
                        JSONArray jsonArray = (JSONArray) title;
                        List<UieComponentVo> tmpList = new ArrayList<>();
                        for (Object o : jsonArray) {
                            UieComponentVo uieTitleVo;
                            uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                            tmpList.add(uieTitleVo);
                        }
                        //对oneList排序
                        tmpList = tmpList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                        listMap.put("title", tmpList);
                    }
                    Object school = result.get("organization");
                    if (null != school) {
                        JSONArray jsonArray = (JSONArray) school;
                        List<UieComponentVo> tmpList = new ArrayList<>();
                        for (Object o : jsonArray) {
                            UieComponentVo uieTitleVo;
                            uieTitleVo = JSON.parseObject(o.toString(), UieComponentVo.class);
                            tmpList.add(uieTitleVo);
                        }
                        //对oneList排序
                        tmpList = tmpList.stream().sorted(Comparator.comparing(UieComponentVo::getStart)).collect(Collectors.toList());
                        listMap.put("school", tmpList);
                    }
                    all_infos.add(listMap);
                }
                return all_infos;
            }
            log.error("uie title response is not 200,textSize:{}, status:{}", texts.size(), response.getStatusLine().getStatusCode());
            return null;
        } catch (IOException | JSONException e) {
            log.error("uie title failed,textSize:{},error:{}", texts.size(), e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        List<String> refs = new ArrayList<>();
        refs.add("[10]葛恒清,王欣.基于Protues的单片机原理及应用教学改革研究.科教导刊：电子版,2018(36):72-73.");
        refs.add("");
        System.out.println(getUieExtractMap(refs));
    }
}
